package com.mjk.common.tools.excel.type;


import com.mjk.common.tools.excel.IFileImportAndExport;
import com.mjk.common.tools.excel.impl.CsvImportAndExportImpl;
import com.mjk.common.tools.excel.impl.ExcelImportAndExportImpl;
import com.mjk.common.tools.excel.impl.XlsxImportAndExportImpl;
import com.mjk.common.util.ReflectionUtils;
import lombok.Getter;

/**
 * 文件类型
 * 
 * @author mjk
 *
 */
public enum FileType {
	XLS("xls", "xls", ExcelImportAndExportImpl.class),
	XLSX("xlsx", "xlsx", XlsxImportAndExportImpl.class),
	CVS("csv", "csv", CsvImportAndExportImpl.class),
	OTHER("other","",null);
	@Getter
	private final String typeName;
	private final String fileEnd;
	private final Class<?> instance;
	FileType(String typeName, String fileEnd, Class<?> instance) {
		this.typeName = typeName;
		this.fileEnd = fileEnd;
		this.instance = instance;
		
	}


	public static String getFileTypeByEnd(String end) {
		for (FileType type : FileType.values()) {
			if (type.fileEnd.contains(end)) {
				return type.typeName;
			}
		}
		return OTHER.typeName;
	}

	public static String getFileTypeByName(String fileName) {
		String end = fileName.substring(fileName.lastIndexOf(".") + 1
        );
		return getFileTypeByEnd(end);
	}
	/**
	 * 根据类型获取处理类型
     */
	public static IFileImportAndExport getFileImportAndExport(String typeName) {
		for (FileType type : FileType.values()) {
			if (type.typeName.contains(typeName)) {
				try {
					return (IFileImportAndExport) ReflectionUtils.newInstance(type.instance);
				}catch(Exception e) {
					return null;
				}
			}
		}
		return null;
	}
	
	public static IFileImportAndExport getFileImportAndExportByFileName(String fileName) {
		String typeName = getFileTypeByName(fileName);
		for (FileType type : FileType.values()) {
			if (type.typeName.contains(typeName)) {
				try {
					return (IFileImportAndExport) ReflectionUtils.newInstance(type.instance);
				}catch(Exception e) {
					return null;
				}
			}
		}
		return null;
	}
}
